package com.dongdongshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.CookieUtils;
import com.dongdongshop.vo.Cart;
import com.dongdongshop.vo.OrderVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {

    @DubboReference
    private CartService cartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private OrderService orderService;

    /*
    * 获取购物车
    * */
    @RequestMapping("addCart")
    public String toAddCart(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response,Model model) {
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        List<Cart> cartList = getCart(request, response);
        cartList = cartService.addCart(itemId, num, cartList);
        TbItem item = cartService.getItemList(itemId);
        model.addAttribute("item",item);
        if (tbUser == null) {
            CookieUtils.setCookie(request, response, "myCookie", JSON.toJSONString(cartList), true);

        }else {
            cartService.saveToRedis(tbUser.getUsername(), cartList);
        }

        return "success-cart";
    }


    @RequestMapping("refreshPage")
    @ResponseBody
    public Result refreshPage(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response,Model model) {
        String s = toAddCart(itemId, num, request, response,model);
        return Result.respones(ResultEnum.SUCCESS);
    }

    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        String cartList = CookieUtils.getCookieValue(request, "myCookie", true);
        if (StringUtils.isBlank(cartList)) {

            cartList = "[]";
        }

        List<Cart> carts = JSONObject.parseArray(cartList, Cart.class);
        if (tbUser == null) {
            return carts;

        }else {
            List<Cart> cartListRedis = cartService.getCartListFormRedis(tbUser.getUsername());
            if (carts.size() > 0) {
                List<Cart> cartListMerge = cartService.mergeCartList(carts, cartListRedis);
                cartService.saveToRedis(tbUser.getUsername(), cartListMerge);
                CookieUtils.deleteCookie(request, response, "myCookie");
                return cartListMerge;
            }

            return cartListRedis;
        }


    }


    @RequestMapping("toCart")
    public String toCart(){
        return "cart";
    }


    @RequestMapping("saveOrder")
    @ResponseBody
    public Result saveOrder(String orders, String orderItems){
        try{
            System.out.println(orders);
            TbUser tu = (TbUser)SecurityUtils.getSubject().getPrincipal();
            List<TbOrder> tos = (List<TbOrder>)JSON.parseArray(orders, TbOrder.class);
            List<TbOrderItem> itemList = (List<TbOrderItem>)JSON.parseArray(orderItems, TbOrderItem.class);
            String orderNumber = orderService.saveOrder(tos, itemList, tu.getUsername());
            TbUser tbUser = (TbUser) SecurityUtils.getSubject().getPrincipal();
            redisTemplate.boundHashOps("cart").put(tbUser.getId(), orderNumber);
            return Result.ok().setData(orderNumber);
        }catch (Exception e){
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("findOrderPayList")
    @ResponseBody
    public Result findOrderPayList(){
        try{
            TbUser tu = (TbUser)SecurityUtils.getSubject().getPrincipal();
            List<OrderVO> list = orderService.findOrderPayList(tu.getUsername());
            return Result.ok().setData(list);
        }catch (Exception e){
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }



}
